<template>
  <section>
    <div v-show="isShow">
      <el-button
        type="primary"
        size="default"
        icon="el-icon-plus"
        style="margin-bottom: 10px"
        @click="isShow = false"
        >添加</el-button
      >
      <el-table :data="newsTable" border stripe>
        <el-table-column label="序号" width="80px" align="center">
          <template v-slot="{ $index }">
            {{ $index + offset + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="420">
        </el-table-column>
        <el-table-column prop="img" label="封面" width="150">
          <template slot-scope="{ row }">
            <el-image :src="row.img" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="简介"> </el-table-column>
        <el-table-column label="发布时间" width="180">
          <template #default="{ row }">
            {{ format(row.createdAt, "yyyy-MM-dd HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="{ row }">
            <el-button
              type="warning"
              icon="el-icon-edit"
              size="mini"
              @click="editData(row)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteItem(row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="newsPagination"
        :hide-on-single-page="true"
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentPage"
      />
    </div>
    <div v-show="!isShow">
      <el-form ref="nForm" :model="nForm" label-width="100px">
        <el-form-item label="标题">
          <el-input v-model="nForm.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/upload"
            :on-success="handleSuccess"
            :show-file-list="false"
          >
            <img v-if="nForm.img" :src="nForm.img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容">
          <Editor v-model="nForm.content" ref="newsEditor" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitData">保存</el-button>
          <el-button @click="cancelNewsForm">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </section>
</template>

<script>
import { format } from "date-fns";
import Editor from "@/components/Tinymce/index.vue";

export default {
  name: "News",
  data() {
    return {
      format,
      isShow: true,
      newsTable: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      nForm: {
        _id: undefined,
        title: "",
        img: "",
        desc: "",
        content: "",
      },
    };
  },
  mounted() {
    this.getNews();
  },
  methods: {
    // 照片图片上传成功的回调
    handleSuccess(response, file, fileList) {
      this.nForm.img = response.data.url;
    },
    // 页面改变
    handleCurrentPage(page) {
      this.currentPage = page;
      this.getNews();
    },
    // 获取所有资讯
    async getNews() {
      let ret = await reqNews({
        offset: this.offset,
        limit: this.pageSize,
      });
      if (ret.code == 200) {
        this.newsTable = ret.data.newsList;
        this.total = ret.data.total;
      }
    },
    async submitData() {
      let activeEditor = this.$refs.newsEditor.tinymce.activeEditor;
      let editBody = activeEditor.getBody();
      activeEditor.selection.select(editBody);
      let text = activeEditor.selection.getContent({ format: "text" });
      this.nForm.desc = text.slice(0, 50);
      let ret = await reqAddOrUpdateNews(this.nForm);
      let tip = this.nForm._id ? "资讯修改成功" : "资讯上传成功";
      if (ret.code == 200) {
        this.getNews();
        this.$message.success(tip);
        this.resetData();
        this.isShow = true;
      }
    },
    editData(item) {
      this.isShow = false;
      this.nForm = { ...item };
    },
    deleteItem(row) {
      this.$confirm(`你确定删除${row.title}?`, "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //当用户点击确定按钮的时候会出发
          //向服务器发请求
          let result = await reqDeleteNews({ id: row._id });
          //如果删除成功
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            if (this.newsTable.length === 1) this.currentPage -= 1;
            this.getNews();
          }
        })
        .catch(() => {
          //当用户点击取消按钮的时候会触发
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    resetData() {
      this.nForm = {
        _id: undefined,
        title: "",
        img: "",
        desc: "",
        content: "",
      };
    },
    cancelNewsForm() {
      this.resetData();
      this.isShow = true;
    },
  },
  computed: {
    offset() {
      return (this.currentPage - 1) * this.pageSize;
    },
  },
  components: {
    Editor,
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.newsPagination {
  display: flex;
  justify-content: center;
  margin-top: 12px;
}
</style>
